package com.inspire.ijc.agent;

import com.inspire.ijc.agent.asminstru.IjcClassWriter;
import com.inspire.ijc.agent.asminstru.ProbeClassVisitor;
import com.inspire.ijc.agent.storage.AllContext;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import java.lang.instrument.ClassFileTransformer;
import java.security.ProtectionDomain;

/**
 * @author ：inspire
 * @date ：Created in 2023/4/13 10:04
 * @description：
 * @modified By：inspire
 * @version:
 */
public class InsertCode implements ClassFileTransformer {

    private final static String deleLoader = "sun.reflect.DelegatingClassLoader";

    @Override
    public byte[] transform(ClassLoader classLoader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) {

        if (!verify(classLoader, className)) {
            return classfileBuffer;
        }

        byte[] resClass = filterClass(classLoader, className, classfileBuffer);
        if (resClass == null) {
            return classfileBuffer;
        } else {
            return resClass;
        }
    }

    private byte[] filterClass(ClassLoader classLoader, String className, byte[] classfileBuffer) {
        try {
            synchronized (classLoader) {

                int classID = AllContext.CLASS_ID_AUTO++;
                boolean classIdExist = false;
                if (AllContext.CLASS_IDS.contains(classID)) {
                    classIdExist = true;
                }
                ClassReader classReader = new ClassReader(classfileBuffer);
                ClassWriter classWriter = new IjcClassWriter(classReader, ClassWriter.COMPUTE_FRAMES, classLoader);
                //这里没有使用Opcodes.ASM7而是直接使用的对应的值458752，原因：有些环境会更改api值，导致使用asm时报错"This feature requires ASM7"，将api值给定可以解决特定环境的报错
                ClassVisitor classVisitor = new ProbeClassVisitor(458752, classWriter, className, classIdExist);
                classReader.accept(classVisitor, ClassReader.SKIP_FRAMES);
                classWriter.visitEnd();

                return classWriter.toByteArray();
            }

        } catch (Exception e) {
            return classfileBuffer;
        }
    }

    public boolean verify(ClassLoader classLoader, String className) {
        if (classLoader == null || className == null || classLoader.getClass().getName().equals(deleLoader)) {
            // skip boot loader, null classes (hibernate), or those from a reflection loader
            return false;
        }

        if (classLoader == null || className == null) {
            return false;
        }

        if (className.startsWith("com/inspire/ijc")) {
            return false;
        }

        if (!IjcAgent.wmIncludes.matches(className)) {
            return false;
        }

        if (IjcAgent.wmExcludes != null) {
            if (IjcAgent.wmExcludes.matches(className)) {
                return false;
            }
        }
        return true;
    }

}
